package server.net.handler;

import java.nio.ByteBuffer;
import server.net.Client;
import server.net.ClientConnection;
import shared.net.protocol.PacketCreator;
import shared.util.PacketIO;

/**
 * Handles a client's login request
 * @author Andrew Gratta
 * @author Vincent Tsuei
 * @version 2012-11-21
 */
public class LoginHandler implements ServerPacketHandler {

    @Override
    public int processPacket(Client client, ByteBuffer packet) {
        if (client == null || packet == null)
        {
            return -1;
        }
        
        ClientConnection connection = client.getConnection();
        
        
        
        // Read in name
        String name = PacketIO.readString(packet);
        // Restrict user names to 3 - 20 characters.
        if (name.length() < 3 || name.length() > 20) {
            connection.queuePacketSend(PacketCreator.LOGIN.getLoginFailureResposne(
                "Your user name must be between 3 and 20 characters long."));
            return -2;
        }
        
        // Check is client is logged in already.
        if (client.isLoggedIn()) {
            connection.queuePacketSend(PacketCreator.LOGIN.getLoginFailureResposne("You are already logged in as: " + client.getPlayer().getName()));
            return -3;
        }
        
        // Let client object handle login.
        int login = client.login(name);
        if (login == 0)
        {
            connection.queuePacketSend(PacketCreator.LOGIN.getLoginSuccessResponse());
        } else {
            connection.queuePacketSend(PacketCreator.LOGIN.getLoginFailureResposne("This username is invalid or is already being used"));
        }
        return login;
    }
    
}
